Load needed libraries
library(fastDummies)
library(readr)
library(ggplot2)
library(dplyr)
library(caret)
library(glmnet)
library(boot)
library(tree)
library(ranger)
library(xgboost)
library(gbm)
library(vip)
library(ISLR)
Set the seed for reproducibility
set.seed(1)
Load the dataset
original_lc_data <- read.csv("LCdata.csv",sep = ";")
lc_data <- original_lc_data
remove attributes not available for prediction
lc_data <- subset(lc_data, select = -c(collection_recovery_fee, installment, issue_d,
last_pymnt_amnt, last_pymnt_d, loan_status,
next_pymnt_d, out_prncp, out_prncp_inv,
pymnt_plan, recoveries,
term, total_pymnt,
total_pymnt_inv,total_rec_int, total_rec_late_fee, total_rec_prncp))
summary(lc_data)
id member_id loan_amnt funded_amnt funded_amnt_inv int_rate
Min. : 54734 Min. : 70473 Min. : 500 Min. : 500 Min. : 0 Min. : 5.32
1st Qu.: 9207230 1st Qu.:10877939 1st Qu.: 8000 1st Qu.: 8000 1st Qu.: 8000 1st Qu.: 9.99
Median :34433372 Median :37095300 Median :13000 Median :13000 Median :13000 Median :12.99
Mean :32463636 Mean :35000265 Mean :14754 Mean :14741 Mean :14702 Mean :13.24
3rd Qu.:54900100 3rd Qu.:58470266 3rd Qu.:20000 3rd Qu.:20000 3rd Qu.:20000 3rd Qu.:16.20
Max. :68617057 Max. :73544841 Max. :35000 Max. :35000 Max. :35000 Max. :28.99
emp_title emp_length home_ownership annual_inc verification_status url
Length:798641 Length:798641 Length:798641 Min. : 0 Length:798641 Length:798641
Class :character Class :character Class :character 1st Qu.: 45000 Class :character Class :character
Mode :character Mode :character Mode :character Median : 65000 Mode :character Mode :character
Mean : 75014
3rd Qu.: 90000
Max. :9500000
NA's :4
desc purpose title zip_code addr_state dti
Length:798641 Length:798641 Length:798641 Length:798641 Length:798641 Min. : 0.00
Class :character Class :character Class :character Class :character Class :character 1st Qu.: 11.91
Mode :character Mode :character Mode :character Mode :character Mode :character Median : 17.66
Mean : 18.16
3rd Qu.: 23.95
Max. :9999.00
delinq_2yrs earliest_cr_line inq_last_6mths mths_since_last_delinq mths_since_last_record
Min. : 0.0000 Length:798641 Min. : 0.0000 Min. : 0.0 Min. : 0.0
1st Qu.: 0.0000 Class :character 1st Qu.: 0.0000 1st Qu.: 15.0 1st Qu.: 51.0
Median : 0.0000 Mode :character Median : 0.0000 Median : 31.0 Median : 70.0
Mean : 0.3145 Mean : 0.6947 Mean : 34.1 Mean : 70.1
3rd Qu.: 0.0000 3rd Qu.: 1.0000 3rd Qu.: 50.0 3rd Qu.: 92.0
Max. :39.0000 Max. :33.0000 Max. :188.0 Max. :129.0
NA's :25 NA's :25 NA's :408818 NA's :675190
open_acc pub_rec revol_bal revol_util total_acc initial_list_status
Min. : 0.00 Min. : 0.0000 Min. : 0 Min. : 0.00 Min. : 1.00 Length:798641
1st Qu.: 8.00 1st Qu.: 0.0000 1st Qu.: 6443 1st Qu.: 37.70 1st Qu.: 17.00 Class :character
Median :11.00 Median : 0.0000 Median : 11876 Median : 56.00 Median : 24.00 Mode :character
Mean :11.55 Mean : 0.1953 Mean : 16930 Mean : 55.05 Mean : 25.27
3rd Qu.:14.00 3rd Qu.: 0.0000 3rd Qu.: 20839 3rd Qu.: 73.50 3rd Qu.: 32.00
Max. :90.00 Max. :63.0000 Max. :2904836 Max. :892.30 Max. :169.00
NA's :25 NA's :25 NA's :2 NA's :454 NA's :25
last_credit_pull_d collections_12_mths_ex_med mths_since_last_major_derog policy_code application_type
Length:798641 Min. : 0.00000 Min. : 0.0 Min. :1 Length:798641
Class :character 1st Qu.: 0.00000 1st Qu.: 27.0 1st Qu.:1 Class :character
Mode :character Median : 0.00000 Median : 44.0 Median :1 Mode :character
Mean : 0.01447 Mean : 44.1 Mean :1
3rd Qu.: 0.00000 3rd Qu.: 61.0 3rd Qu.:1
Max. :20.00000 Max. :188.0 Max. :1
NA's :126 NA's :599107
annual_inc_joint dti_joint verification_status_joint acc_now_delinq tot_coll_amt
Min. : 17950 Min. : 3.0 Length:798641 Min. : 0.000000 Min. : 0
1st Qu.: 76167 1st Qu.:13.3 Class :character 1st Qu.: 0.000000 1st Qu.: 0
Median :101886 Median :17.7 Mode :character Median : 0.000000 Median : 0
Mean :110745 Mean :18.4 Mean : 0.005026 Mean : 228
3rd Qu.:133000 3rd Qu.:22.6 3rd Qu.: 0.000000 3rd Qu.: 0
Max. :500000 Max. :43.9 Max. :14.000000 Max. :9152545
NA's :798181 NA's :798183 NA's :25 NA's :63276
tot_cur_bal open_acc_6m open_il_6m open_il_12m open_il_24m mths_since_rcnt_il
Min. : 0 Min. : 0.0 Min. : 0.0 Min. : 0.0 Min. : 0.0 Min. : 0.0
1st Qu.: 29861 1st Qu.: 0.0 1st Qu.: 1.0 1st Qu.: 0.0 1st Qu.: 0.0 1st Qu.: 6.0
Median : 80647 Median : 1.0 Median : 2.0 Median : 0.0 Median : 1.0 Median : 12.0
Mean : 139508 Mean : 1.1 Mean : 2.9 Mean : 0.8 Mean : 1.7 Mean : 21.1
3rd Qu.: 208229 3rd Qu.: 2.0 3rd Qu.: 4.0 3rd Qu.: 1.0 3rd Qu.: 2.0 3rd Qu.: 23.0
Max. :8000078 Max. :14.0 Max. :33.0 Max. :12.0 Max. :19.0 Max. :363.0
NA's :63276 NA's :779525 NA's :779525 NA's :779525 NA's :779525 NA's :780030
total_bal_il il_util open_rv_12m open_rv_24m max_bal_bc all_util
Min. : 0 Min. : 0.0 Min. : 0.0 Min. : 0 Min. : 0 Min. : 0.0
1st Qu.: 10164 1st Qu.: 58.4 1st Qu.: 0.0 1st Qu.: 1 1st Qu.: 2406 1st Qu.: 47.6
Median : 24544 Median : 74.8 Median : 1.0 Median : 2 Median : 4502 Median : 61.9
Mean : 36428 Mean : 71.5 Mean : 1.4 Mean : 3 Mean : 5878 Mean : 60.8
3rd Qu.: 47640 3rd Qu.: 87.7 3rd Qu.: 2.0 3rd Qu.: 4 3rd Qu.: 7774 3rd Qu.: 75.2
Max. :878459 Max. :223.3 Max. :22.0 Max. :43 Max. :83047 Max. :151.4
NA's :779525 NA's :782007 NA's :779525 NA's :779525 NA's :779525 NA's :779525
total_rev_hi_lim inq_fi total_cu_tl inq_last_12m
Min. : 0 Min. : 0.0 Min. : 0.0 Min. :-4
1st Qu.: 13900 1st Qu.: 0.0 1st Qu.: 0.0 1st Qu.: 0
Median : 23700 Median : 0.0 Median : 0.0 Median : 2
Mean : 32093 Mean : 0.9 Mean : 1.5 Mean : 2
3rd Qu.: 39800 3rd Qu.: 1.0 3rd Qu.: 2.0 3rd Qu.: 3
Max. :9999999 Max. :16.0 Max. :35.0 Max. :32
NA's :63276 NA's :779525 NA's :779525 NA's :779525
First we delete the columns which aren’t useful for our prediction
lc_data$id <- NULL
lc_data$member_id <- NULL
lc_data$zip_code <- NULL
lc_data$url <- NULL
Looks like policy_code contains just value equal to 1, it can be removed
lc_data$policy_code <- NULL
Remove additional columns which are related to the historical data
lc_data$last_credit_pull_d <- NULL
Then we delete the columns which can’t be converted to categorical and require NLP
lc_data$title <- NULL
lc_data$desc <- NULL
lc_data$emp_title <- NULL
let’s examine the loan_amnt column
sum(is.na(lc_data$loan_amnt))
[1] 0
cor(lc_data$loan_amnt, lc_data$int_rate)
[1] 0.1447189
hist(lc_data$loan_amnt, breaks = 20, main = "loan_amnt distribution", xlab = "loan_amnt", col = "lightblue", border = "black")
ggplot(data = lc_data, mapping = aes(x=int_rate,y=loan_amnt)) + geom_boxplot()
standardize loan_amnt
#lc_data$loan_amnt <- scale(lc_data$loan_amnt)
let’s examine the funded_amnt column
sum(is.na(lc_data$funded_amnt))
[1] 0
cor(lc_data$funded_amnt, lc_data$int_rate)
[1] 0.1448634
hist(lc_data$funded_amnt, breaks = 20, main = "funded_amnt distribution", xlab = "funded_amnt", col = "lightblue", border = "black")
as we can see, funded_amnt is almost the same as the loan_amnt column, consequently, we remove it.
lc_data$funded_amnt <- NULL
let’s examine the funded_amnt_inv column
sum(is.na(lc_data$funded_amnt_inv))
[1] 0
cor(lc_data$funded_amnt_inv, lc_data$int_rate)
[1] 0.1449083
hist(lc_data$funded_amnt_inv, breaks = 20, main = "funded_amnt_inv distribution", xlab = "funded_amnt_inv", col = "lightblue", border = "black")
remove funded_amnt_inv for the same reason as above
lc_data$funded_amnt_inv <- NULL
let’s see the int_rate distribution.
hist(lc_data$int_rate, breaks = 20, main = "int_rate distribution", xlab = "int_rate", col = "lightblue", border = "black")
Standardize int rate:
#lc_data$int_rate <- scale(lc_data$int_rate)
we delete the emp_title column as there are several entries for the same job title and because there are too many different values for one-hot encoding. In addition, some titles are unclear (NLP required)
n_distinct(lc_data$emp_title)
[1] 0
As we can observe, there are 40363 NAs. We can assume 40363 do not work.
barplot(table(lc_data$emp_length),
xlab = "emp_length years",
ylab = "Frequency",
col = "skyblue",
border = "black",
cex.names = 0.6) # The size of the main title
Since emp_length seems to be categorical, we transform it to as a factor and then as numeric. The conversion to numeric is needed for supporting the XGBoost
lc_data$emp_length <- as.factor(lc_data$emp_length)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=emp_length)) + geom_boxplot()
lc_data$emp_length <- as.numeric(lc_data$emp_length)
Cleaning of home_ownership:
During the data cleaning phase, our analysis revealed that the variable “home_ownership” does not show a distinct correlation with interest rates. Specifically, among the categories, “ANY” and “OTHER” contain 2 and 154 cases, respectively, while the “NONE” category comprises 39 cases. Although the “NONE” category appears to demonstrate a higher interest rate compared to others, the limited sample size of 39 cases raises doubts about the reliability of this observation. Notably, the “NONE” category might pertain to individuals experiencing homelessness, prompting ethical concerns about loan provision to this demographic.
table(lc_data$home_ownership)
ANY MORTGAGE NONE OTHER OWN RENT
2 399151 45 155 78789 320499
ggplot(data = lc_data, mapping = aes(x=int_rate,y=home_ownership)) + geom_boxplot()
Then, we retain mortgage, own and rent:
lc_data <- lc_data %>% filter(home_ownership %in% c("MORTGAGE","OWN","RENT"))
lc_data$home_ownership <- as.numeric(as.factor(lc_data$home_ownership))
# merging annual income
lc_data <- lc_data %>% mutate(
annual_inc_merged = ifelse(is.na(annual_inc_joint)== TRUE, annual_inc,annual_inc_joint))
lc_data <- lc_data %>% select(-annual_inc,-annual_inc_joint)
# merging debt to income ratio
lc_data <- lc_data %>% mutate(
dti_merged = ifelse(is.na(dti_joint)== TRUE, dti,dti_joint))
lc_data <- lc_data %>% select(-dti,-dti_joint)
Upon reviewing the summary again, it becomes apparent that there are merely 460 joint applications, constituting a small subset within the extensive dataset of around 800k rows. Through consolidating the debt-to-income ratios (dti’s), we can pinpoint the data pertinent to our research objectives. Hence, it is advisable to eliminate the columns verification_status_joint and application_type to prevent introducing unwarranted variability into our analysis.
table(lc_data$verification_status)
Not Verified Source Verified Verified
240255 296631 261553
table(lc_data$verification_status_joint)
Not Verified Source Verified Verified
797979 253 53 154
lc_data$verification_status <- as.numeric(as.factor(lc_data$verification_status))
lc_data <- lc_data %>% select(-verification_status_joint, -application_type)
Let’s checl if other is NA or a real value for purpose. It’s a real one, so we don’t have to handle it.
lc_data$purpose <- as.factor(lc_data$purpose)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=purpose)) + geom_boxplot()
lc_data$purpose <- as.numeric(lc_data$purpose)
Let’s have a glance to the state address:
table(lc_data$addr_state)
AK AL AR AZ CA CO CT DC DE FL GA HI IA ID IL IN
1992 10101 5953 18359 116578 16934 12154 2188 2268 54819 26146 4112 13 11 31880 12393
KS KY LA MA MD ME MI MN MO MS MT NC ND NE NH NJ
7105 7726 9498 18546 18906 469 20678 14306 12821 3455 2286 22135 431 1064 3865 29991
NM NV NY OH OK OR PA RI SC SD TN TX UT VA VT WA
4428 11155 66790 26682 7266 9806 28221 3499 9609 1615 11618 63982 5629 23616 1606 17470
WI WV WY
10446 3977 1841
lc_data$addr_state <- as.factor(lc_data$addr_state)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=addr_state)) + geom_boxplot()
lc_data$addr_state <- as.numeric(lc_data$addr_state)
Regarding delinquency in the last 2 years, there are few NAs then remove them:
lc_data <- lc_data %>%
filter(!(is.na(delinq_2yrs)))
lc_data <- lc_data %>%
mutate(mths_since_delinq_cat = ifelse(
is.na(mths_since_last_delinq) == TRUE,
"NONE",
ifelse(
mths_since_last_delinq <= 12,
"Less_1_Y",
ifelse(
mths_since_last_delinq <= 24,
"Less_2_Y",
ifelse(
mths_since_last_delinq <= 36,
"Less_3_Y",
ifelse(mths_since_last_delinq <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_last_delinq)
lc_data$mths_since_delinq_cat <- as.factor(lc_data$mths_since_delinq_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_delinq_cat))+geom_boxplot()
lc_data$mths_since_delinq_cat <- as.numeric(lc_data$mths_since_delinq_cat)
lc_data <- lc_data %>%
mutate(mths_since_last_record_cat = ifelse(
is.na(mths_since_last_record) == TRUE,
"NONE",
ifelse(
mths_since_last_record <= 12,
"Less_1_Y",
ifelse(
mths_since_last_record <= 24,
"Less_2_Y",
ifelse(
mths_since_last_record <= 36,
"Less_3_Y",
ifelse(mths_since_last_record <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_last_record)
lc_data$mths_since_last_record_cat <- as.factor(lc_data$mths_since_last_record_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_last_record_cat))+geom_boxplot()
lc_data$mths_since_last_record_cat <- as.numeric(lc_data$mths_since_last_record_cat)
lc_data <-lc_data %>%
mutate(mths_since_last_major_derog_cat = ifelse(
is.na(mths_since_last_major_derog) == TRUE,
"NONE",
ifelse(
mths_since_last_major_derog <= 12,
"Less_1_Y",
ifelse(
mths_since_last_major_derog <= 24,
"Less_2_Y",
ifelse(
mths_since_last_major_derog <= 36,
"Less_3_Y",
ifelse(mths_since_last_major_derog <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_last_major_derog)
lc_data$mths_since_last_major_derog_cat <- as.factor(lc_data$mths_since_last_major_derog_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_last_major_derog_cat))+geom_boxplot()
lc_data$mths_since_last_major_derog_cat <- as.numeric(lc_data$mths_since_last_major_derog_cat)
lc_data$initial_list_status <- as.factor(lc_data$initial_list_status)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=initial_list_status))+geom_boxplot()
lc_data$initial_list_status <- as.numeric(lc_data$initial_list_status)
Let’s check which columns still have null values
colSums(is.na(lc_data))
loan_amnt int_rate emp_length
0 0 0
home_ownership verification_status purpose
0 0 0
addr_state delinq_2yrs earliest_cr_line
0 0 0
inq_last_6mths open_acc pub_rec
0 0 0
revol_bal revol_util total_acc
2 428 0
initial_list_status collections_12_mths_ex_med acc_now_delinq
0 99 0
tot_coll_amt tot_cur_bal open_acc_6m
63132 63132 779302
open_il_6m open_il_12m open_il_24m
779302 779302 779302
mths_since_rcnt_il total_bal_il il_util
779807 779302 781784
open_rv_12m open_rv_24m max_bal_bc
779302 779302 779302
all_util total_rev_hi_lim inq_fi
779302 63132 779302
total_cu_tl inq_last_12m annual_inc_merged
779302 779302 0
dti_merged mths_since_delinq_cat mths_since_last_record_cat
0 0 0
mths_since_last_major_derog_cat
0
The columns revol_bal and revol_util contain only few NA values, those values can’t be replaced with 0, then we filter the values which are not NA
lc_data <- lc_data %>%
filter(!(is.na(revol_bal))) %>%
filter(!(is.na(revol_util)))
Let’s check which columns still have null values
names(which(colSums(is.na(lc_data)) > 0))
[1] "collections_12_mths_ex_med" "tot_coll_amt" "tot_cur_bal"
[4] "open_acc_6m" "open_il_6m" "open_il_12m"
[7] "open_il_24m" "mths_since_rcnt_il" "total_bal_il"
[10] "il_util" "open_rv_12m" "open_rv_24m"
[13] "max_bal_bc" "all_util" "total_rev_hi_lim"
[16] "inq_fi" "total_cu_tl" "inq_last_12m"
Replace null values with 0 where is possible
lc_data <-
lc_data %>%
mutate(open_acc_6m = ifelse(is.na(open_acc_6m) == TRUE, 0, open_acc_6m)) %>%
mutate(tot_cur_bal = ifelse(is.na(tot_cur_bal) == TRUE, 0, tot_cur_bal)) %>%
mutate(open_il_6m = ifelse(is.na(open_il_6m) == TRUE, 0, open_il_6m)) %>%
mutate(open_il_12m = ifelse(is.na(open_il_12m) == TRUE, 0, open_il_12m)) %>%
mutate(open_il_24m = ifelse(is.na(open_il_24m) == TRUE, 0, open_il_24m)) %>%
mutate(mths_since_rcnt_il = ifelse(is.na(mths_since_rcnt_il) == TRUE, 0, mths_since_rcnt_il)) %>%
mutate(total_bal_il = ifelse(is.na(total_bal_il) == TRUE, 0, total_bal_il)) %>%
mutate(il_util = ifelse(is.na(il_util) == TRUE, 0, il_util)) %>%
mutate(open_rv_12m = ifelse(is.na(open_rv_12m) == TRUE, 0, open_rv_12m)) %>%
mutate(total_rev_hi_lim = ifelse(is.na(total_rev_hi_lim) == TRUE, 0, total_rev_hi_lim)) %>%
mutate(max_bal_bc = ifelse(is.na(max_bal_bc) == TRUE, 0, max_bal_bc)) %>%
mutate(all_util = ifelse(is.na(all_util) == TRUE, 0, all_util)) %>%
mutate(inq_fi = ifelse(is.na(inq_fi) == TRUE, 0, inq_fi)) %>%
mutate(total_cu_tl = ifelse(is.na(total_cu_tl) == TRUE, 0, total_cu_tl)) %>%
mutate(inq_last_12m = ifelse(is.na(inq_last_12m) == TRUE, 0, inq_last_12m)) %>%
mutate(open_rv_24m = ifelse(is.na(open_rv_24m) == TRUE, 0, open_rv_24m)) %>%
mutate(tot_coll_amt = ifelse(is.na(tot_coll_amt)== TRUE,0, tot_coll_amt)) %>%
mutate(collections_12_mths_ex_med = ifelse(is.na(collections_12_mths_ex_med)== TRUE,0, collections_12_mths_ex_med))
earliest_cr_line contains the month the borrower’s earliest reported credit line was opened. Even if this date consists only on month and year, still there are too many unique values. We could transform the dates in to a numerical value, by converting them from date into Unix Time. This unit measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970. Since this column doesn’t contain the day number, we take as a reference the first day of the month.
lc_data <- lc_data %>%
filter(!(is.na(earliest_cr_line)))
# function to replace dates with unix time
to_unix_time <- function(date) {
tmp <- paste("01", date, sep="-")
return (as.numeric(as.POSIXct(tmp, format="%d-%b-%Y", tz="UTC")))
}
# map dates to unix time
lc_data$earliest_cr_line <- apply(lc_data, 1, function(row) to_unix_time(row["earliest_cr_line"]))
# standardize them
#lc_data$earliest_cr_line <- scale(lc_data$earliest_cr_line)
summary(lc_data)
loan_amnt int_rate emp_length home_ownership verification_status purpose
Min. : 500 Min. : 5.32 Min. : 1.00 Min. :1.000 Min. :1.000 Min. : 1.000
1st Qu.: 8000 1st Qu.: 9.99 1st Qu.: 3.00 1st Qu.:1.000 1st Qu.:1.000 1st Qu.: 3.000
Median :13000 Median :12.99 Median : 4.00 Median :2.000 Median :2.000 Median : 3.000
Mean :14757 Mean :13.24 Mean : 5.11 Mean :1.901 Mean :2.027 Mean : 3.571
3rd Qu.:20000 3rd Qu.:16.20 3rd Qu.: 7.00 3rd Qu.:3.000 3rd Qu.:3.000 3rd Qu.: 3.000
Max. :35000 Max. :28.99 Max. :12.00 Max. :3.000 Max. :3.000 Max. :14.000
addr_state delinq_2yrs earliest_cr_line inq_last_6mths open_acc pub_rec
Min. : 1.00 Min. : 0.0000 Min. :-820540800 Min. : 0.0000 Min. : 1.00 Min. : 0.0000
1st Qu.:10.00 1st Qu.: 0.0000 1st Qu.: 770428800 1st Qu.: 0.0000 1st Qu.: 8.00 1st Qu.: 0.0000
Median :24.00 Median : 0.0000 Median : 936144000 Median : 0.0000 Median :11.00 Median : 0.0000
Mean :24.14 Mean : 0.3143 Mean : 889273164 Mean : 0.6947 Mean :11.55 Mean : 0.1954
3rd Qu.:37.00 3rd Qu.: 0.0000 3rd Qu.:1051747200 3rd Qu.: 1.0000 3rd Qu.:14.00 3rd Qu.: 0.0000
Max. :51.00 Max. :39.0000 Max. :1351728000 Max. :33.0000 Max. :90.00 Max. :63.0000
revol_bal revol_util total_acc initial_list_status collections_12_mths_ex_med
Min. : 0 Min. : 0.00 Min. : 1.00 Min. :1.000 Min. : 0.00000
1st Qu.: 6450 1st Qu.: 37.70 1st Qu.: 17.00 1st Qu.:1.000 1st Qu.: 0.00000
Median : 11881 Median : 56.00 Median : 24.00 Median :1.000 Median : 0.00000
Mean : 16934 Mean : 55.05 Mean : 25.27 Mean :1.485 Mean : 0.01448
3rd Qu.: 20844 3rd Qu.: 73.50 3rd Qu.: 32.00 3rd Qu.:2.000 3rd Qu.: 0.00000
Max. :2904836 Max. :892.30 Max. :169.00 Max. :2.000 Max. :20.00000
acc_now_delinq tot_coll_amt tot_cur_bal open_acc_6m open_il_6m open_il_12m
Min. : 0.000000 Min. : 0 Min. : 0 Min. : 0.00000 Min. : 0.00000 Min. : 0.00000
1st Qu.: 0.000000 1st Qu.: 0 1st Qu.: 23195 1st Qu.: 0.00000 1st Qu.: 0.00000 1st Qu.: 0.00000
Median : 0.000000 Median : 0 Median : 65402 Median : 0.00000 Median : 0.00000 Median : 0.00000
Mean : 0.005026 Mean : 210 Mean : 128461 Mean : 0.02641 Mean : 0.06982 Mean : 0.01816
3rd Qu.: 0.000000 3rd Qu.: 0 3rd Qu.: 195864 3rd Qu.: 0.00000 3rd Qu.: 0.00000 3rd Qu.: 0.00000
Max. :14.000000 Max. :9152545 Max. :8000078 Max. :14.00000 Max. :33.00000 Max. :12.00000
open_il_24m mths_since_rcnt_il total_bal_il il_util open_rv_12m open_rv_24m
Min. : 0.00000 Min. : 0.0000 Min. : 0 Min. : 0.000 Min. : 0.00000 Min. : 0.00000
1st Qu.: 0.00000 1st Qu.: 0.0000 1st Qu.: 0 1st Qu.: 0.000 1st Qu.: 0.00000 1st Qu.: 0.00000
Median : 0.00000 Median : 0.0000 Median : 0 Median : 0.000 Median : 0.00000 Median : 0.00000
Mean : 0.03991 Mean : 0.4918 Mean : 872 Mean : 1.489 Mean : 0.03316 Mean : 0.07114
3rd Qu.: 0.00000 3rd Qu.: 0.0000 3rd Qu.: 0 3rd Qu.: 0.000 3rd Qu.: 0.00000 3rd Qu.: 0.00000
Max. :19.00000 Max. :363.0000 Max. :878459 Max. :223.300 Max. :22.00000 Max. :43.00000
max_bal_bc all_util total_rev_hi_lim inq_fi total_cu_tl inq_last_12m
Min. : 0.0 Min. : 0.000 Min. : 0 Min. : 0.00000 Min. : 0.00000 Min. :-4.00000
1st Qu.: 0.0 1st Qu.: 0.000 1st Qu.: 11700 1st Qu.: 0.00000 1st Qu.: 0.00000 1st Qu.: 0.00000
Median : 0.0 Median : 0.000 Median : 21800 Median : 0.00000 Median : 0.00000 Median : 0.00000
Mean : 140.8 Mean : 1.456 Mean : 29564 Mean : 0.02262 Mean : 0.03668 Mean : 0.04733
3rd Qu.: 0.0 3rd Qu.: 0.000 3rd Qu.: 37900 3rd Qu.: 0.00000 3rd Qu.: 0.00000 3rd Qu.: 0.00000
Max. :83047.0 Max. :151.400 Max. :9999999 Max. :16.00000 Max. :35.00000 Max. :32.00000
annual_inc_merged dti_merged mths_since_delinq_cat mths_since_last_record_cat mths_since_last_major_derog_cat
Min. : 1896 Min. : 0.00 Min. :1.000 Min. :1.000 Min. :1.000
1st Qu.: 45000 1st Qu.:11.91 1st Qu.:3.000 1st Qu.:6.000 1st Qu.:6.000
Median : 65000 Median :17.66 Median :6.000 Median :6.000 Median :6.000
Mean : 75038 Mean :18.13 Mean :4.576 Mean :5.779 Mean :5.435
3rd Qu.: 90000 3rd Qu.:23.94 3rd Qu.:6.000 3rd Qu.:6.000 3rd Qu.:6.000
Max. :9500000 Max. :43.86 Max. :6.000 Max. :6.000 Max. :6.000
#round(cor(lc_data),2)
# TODO: (parte vecchia), split 80/20 e linear regression...
# Create indices for splitting (80% train, 20% test)
train_indices <- createDataPartition(lc_data$int_rate, p = 0.8, list = FALSE)
# Create training and testing datasets
train_data <- lc_data[train_indices, ]
test_data <- lc_data[-train_indices, ]
#### Linear Regression ####
#lm.fit <- lm(int_rate ~ ., data = train_data)
# TODO: check collinearity and multicollinearity
#vif(lm.fit) # there is multicollinearity
#cor(lc_data)
# Make predictions on training and testing data
#train_predictions <- predict(lm.fit, newdata = train_data)
#test_predictions <- predict(lm.fit, newdata = test_data)
# Evaluate model performance on training data
#train_rmse <- sqrt(mean((train_predictions - train_data$int_rate)^2))
#train_r_squared <- summary(lm.fit)$r.squared
# Evaluate model performance on testing data
#test_rmse <- sqrt(mean((test_predictions - test_data$int_rate)^2))
#test_r_squared <- summary(lm.fit, test_data)$r.squared
# Print evaluation metrics
#cat("Training RMSE:", train_rmse, "\n")
#cat("Training R-squared:", train_r_squared, "\n")
#rmse <- sqrt(mean(lm.fit$residuals^2))
#print(rmse)
# 1% of the total rows
sample_train_size <- floor(0.01 * nrow(train_data))
sample_test_size <- floor(0.01 * nrow(test_data))
# Randomly select 1% of the rows
sampled_train_data <- train_data[sample(nrow(train_data), size = sample_train_size, replace = FALSE), ]
sampled_test_data <- test_data[sample(nrow(test_data), size = sample_test_size, replace = FALSE), ]
sampled_train_data <- train_data
sampled_test_data <- test_data
#### Linear Regression ####
lm.fit <- lm(int_rate ~ ., data = sampled_train_data)
# Make predictions on the training and testing data
lm.train_predictions <- predict(lm.fit, newdata = sampled_train_data)
lm.test_predictions <- predict(lm.fit, newdata = sampled_test_data)
# Calculate Mean Squared Error (MSE) for training and testing
lm.train_mse <- mean((lm.train_predictions - sampled_train_data$int_rate)^2)
lm.test_mse <- mean((lm.test_predictions - sampled_test_data$int_rate)^2)
# Calculate Root Mean Squared Error (RMSE) for training and testing
lm.train_rmse <- sqrt(lm.train_mse)
lm.test_rmse <- sqrt(lm.test_mse)
# Calculate Mean Absolute Error (MAE) for training and testing
lm.train_mae <- mean(abs(lm.train_predictions - sampled_train_data$int_rate))
lm.test_mae <- mean(abs(lm.test_predictions - sampled_test_data$int_rate))
# Calculate R-squared (R²) for training and testing
lm.train_r2 <- 1 - (sum((sampled_train_data$int_rate - lm.train_predictions)^2) / sum((sampled_train_data$int_rate - mean(sampled_train_data$int_rate))^2))
lm.test_r2 <- 1 - (sum((sampled_test_data$int_rate - lm.test_predictions)^2) / sum((sampled_test_data$int_rate - mean(sampled_test_data$int_rate))^2))
# Display the metrics
cat("Training MSE:", lm.train_mse, "\n")
Training MSE: 13.26248
cat("Testing MSE:", lm.test_mse, "\n")
Testing MSE: 13.6664
cat("Training RMSE:", lm.train_rmse, "\n")
Training RMSE: 3.641768
cat("Testing RMSE:", lm.test_rmse, "\n")
Testing RMSE: 3.696809
cat("Training MAE:", lm.train_mae, "\n")
Training MAE: 2.885102
cat("Testing MAE:", lm.test_mae, "\n")
Testing MAE: 2.889154
cat("Training R-squared (R²):", lm.train_r2, "\n")
Training R-squared (R²): 0.3094189
cat("Testing R-squared (R²):", lm.test_r2, "\n")
Testing R-squared (R²): 0.2880591
#### Linear Regresion applying Cross Validation with k=2 to k=10 ####
# Assuming 'sampled_train_data' is your training data set
# Initialize lists to store models and their results
models <- list()
results <- data.frame()
# Define the number of folds for cross-validation
num_folds <- 10
folds <- createFolds(sampled_train_data$int_rate, k = num_folds, list = TRUE)
# Perform k-fold cross-validation
for(i in seq_along(folds)) {
# Split the data into training and testing for the current fold
train_indices <- folds[[i]]
test_indices <- setdiff(seq_len(nrow(sampled_train_data)), train_indices)
train_data_fold <- sampled_train_data[train_indices, ]
test_data_fold <- sampled_train_data[test_indices, ]
# Fit the model on the training fold
lm_model <- lm(int_rate ~ ., data = train_data_fold)
models[[i]] <- lm_model # Store the model
# Make predictions on the training and testing fold
train_predictions <- predict(lm_model, newdata = train_data_fold)
test_predictions <- predict(lm_model, newdata = test_data_fold)
# Calculate metrics for training fold
train_mse <- mean((train_predictions - train_data_fold$int_rate)^2)
train_rmse <- sqrt(train_mse)
train_mae <- mean(abs(train_predictions - train_data_fold$int_rate))
train_r2 <- summary(lm_model)$r.squared
# Calculate metrics for testing fold
test_mse <- mean((test_predictions - test_data_fold$int_rate)^2)
test_rmse <- sqrt(test_mse)
test_mae <- mean(abs(test_predictions - test_data_fold$int_rate))
test_r2 <- 1 - (sum((test_data_fold$int_rate - test_predictions)^2) / sum((test_data_fold$int_rate - mean(test_data_fold$int_rate))^2))
# Store metrics in the results dataframe
results <- rbind(results, data.frame(
Fold = i,
Train_MSE = train_mse, Test_MSE = test_mse,
Train_RMSE = train_rmse, Test_RMSE = test_rmse,
Train_MAE = train_mae, Test_MAE = test_mae,
Train_R2 = train_r2, Test_R2 = test_r2
))
}
# Display the models and their metrics
print(models)
[[1]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.335e+00 1.261e-04 1.064e-02
home_ownership verification_status purpose
1.931e-01 8.601e-01 3.559e-01
addr_state delinq_2yrs earliest_cr_line
2.676e-03 4.429e-02 2.146e-09
inq_last_6mths open_acc pub_rec
9.875e-01 6.126e-02 4.337e-01
revol_bal revol_util total_acc
8.094e-06 4.396e-02 -3.199e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-6.185e-01 2.261e-01 1.500e+00
tot_coll_amt tot_cur_bal open_acc_6m
2.307e-05 -1.057e-06 -1.049e-01
open_il_6m open_il_12m open_il_24m
-1.773e-01 6.202e-01 8.539e-02
mths_since_rcnt_il total_bal_il il_util
-7.375e-03 1.206e-06 -1.392e-04
open_rv_12m open_rv_24m max_bal_bc
2.434e-01 4.545e-03 -4.965e-05
all_util total_rev_hi_lim inq_fi
-6.684e-03 -2.158e-05 4.006e-02
total_cu_tl inq_last_12m annual_inc_merged
-5.500e-02 6.120e-02 -7.378e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
6.407e-02 -1.807e-01 -1.394e-01
mths_since_last_major_derog_cat
-1.629e-01
[[2]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.495e+00 1.238e-04 2.940e-03
home_ownership verification_status purpose
1.369e-01 8.660e-01 3.471e-01
addr_state delinq_2yrs earliest_cr_line
1.515e-03 1.398e-02 2.024e-09
inq_last_6mths open_acc pub_rec
1.008e+00 6.684e-02 3.921e-01
revol_bal revol_util total_acc
4.134e-06 4.416e-02 -3.255e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-6.204e-01 3.396e-01 1.791e+00
tot_coll_amt tot_cur_bal open_acc_6m
1.774e-05 -1.541e-06 1.707e-01
open_il_6m open_il_12m open_il_24m
-2.146e-01 6.587e-01 -1.285e-01
mths_since_rcnt_il total_bal_il il_util
-9.629e-03 4.188e-06 -7.130e-03
open_rv_12m open_rv_24m max_bal_bc
5.293e-02 1.003e-01 -1.012e-04
all_util total_rev_hi_lim inq_fi
6.933e-03 -2.038e-05 1.058e-03
total_cu_tl inq_last_12m annual_inc_merged
-7.185e-02 5.545e-02 -4.952e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
7.052e-02 -2.070e-01 -1.483e-01
mths_since_last_major_derog_cat
-1.465e-01
[[3]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.795e+00 1.227e-04 3.673e-03
home_ownership verification_status purpose
1.796e-01 8.496e-01 3.794e-01
addr_state delinq_2yrs earliest_cr_line
2.056e-03 4.228e-02 2.071e-09
inq_last_6mths open_acc pub_rec
1.040e+00 4.118e-02 3.960e-01
revol_bal revol_util total_acc
-8.947e-06 5.120e-02 -2.648e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-7.368e-01 4.090e-01 1.264e+00
tot_coll_amt tot_cur_bal open_acc_6m
3.001e-05 -1.351e-06 3.791e-03
open_il_6m open_il_12m open_il_24m
-1.259e-01 7.328e-01 -1.338e-01
mths_since_rcnt_il total_bal_il il_util
-1.066e-02 1.841e-06 -6.795e-03
open_rv_12m open_rv_24m max_bal_bc
2.146e-01 -7.199e-03 -8.579e-05
all_util total_rev_hi_lim inq_fi
4.057e-03 -1.006e-06 5.499e-02
total_cu_tl inq_last_12m annual_inc_merged
-5.518e-02 6.357e-02 -9.088e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
6.126e-02 -2.122e-01 -2.423e-01
mths_since_last_major_derog_cat
-1.384e-01
[[4]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.669e+00 1.203e-04 8.399e-03
home_ownership verification_status purpose
1.705e-01 8.574e-01 3.508e-01
addr_state delinq_2yrs earliest_cr_line
9.598e-04 5.734e-02 2.017e-09
inq_last_6mths open_acc pub_rec
9.963e-01 6.263e-02 3.850e-01
revol_bal revol_util total_acc
1.191e-05 4.117e-02 -3.385e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-6.315e-01 2.786e-01 1.662e+00
tot_coll_amt tot_cur_bal open_acc_6m
1.838e-05 -9.500e-07 -3.635e-02
open_il_6m open_il_12m open_il_24m
-1.334e-01 4.343e-01 1.271e-01
mths_since_rcnt_il total_bal_il il_util
-8.521e-03 4.237e-06 -4.376e-03
open_rv_12m open_rv_24m max_bal_bc
7.466e-02 1.385e-01 -6.254e-05
all_util total_rev_hi_lim inq_fi
-7.971e-03 -2.401e-05 1.278e-01
total_cu_tl inq_last_12m annual_inc_merged
-1.062e-01 5.820e-02 -4.855e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
6.929e-02 -1.944e-01 -1.617e-01
mths_since_last_major_derog_cat
-1.483e-01
[[5]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.625e+00 1.279e-04 1.136e-02
home_ownership verification_status purpose
1.935e-01 8.283e-01 3.525e-01
addr_state delinq_2yrs earliest_cr_line
1.137e-03 -6.451e-03 2.030e-09
inq_last_6mths open_acc pub_rec
1.054e+00 6.369e-02 4.255e-01
revol_bal revol_util total_acc
6.297e-06 4.456e-02 -3.225e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-5.496e-01 5.413e-01 1.546e+00
tot_coll_amt tot_cur_bal open_acc_6m
2.647e-05 -9.294e-07 3.598e-02
open_il_6m open_il_12m open_il_24m
-1.076e-01 5.165e-01 5.002e-02
mths_since_rcnt_il total_bal_il il_util
-3.113e-03 1.363e-06 -1.340e-03
open_rv_12m open_rv_24m max_bal_bc
1.594e-01 -2.279e-02 -8.140e-05
all_util total_rev_hi_lim inq_fi
-8.735e-03 -2.197e-05 2.062e-02
total_cu_tl inq_last_12m annual_inc_merged
-6.251e-02 1.092e-01 -7.380e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
6.384e-02 -2.054e-01 -1.808e-01
mths_since_last_major_derog_cat
-1.441e-01
[[6]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.226e+00 1.216e-04 3.531e-04
home_ownership verification_status purpose
1.819e-01 8.539e-01 3.753e-01
addr_state delinq_2yrs earliest_cr_line
2.751e-04 2.613e-02 2.194e-09
inq_last_6mths open_acc pub_rec
1.050e+00 4.567e-02 5.423e-01
revol_bal revol_util total_acc
-8.489e-06 5.094e-02 -2.840e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-7.601e-01 4.038e-01 1.302e+00
tot_coll_amt tot_cur_bal open_acc_6m
2.311e-05 -1.091e-06 1.343e-01
open_il_6m open_il_12m open_il_24m
-1.506e-01 6.102e-01 4.087e-02
mths_since_rcnt_il total_bal_il il_util
-7.501e-03 4.745e-06 -3.830e-03
open_rv_12m open_rv_24m max_bal_bc
2.662e-01 -1.898e-02 -9.227e-05
all_util total_rev_hi_lim inq_fi
-4.138e-03 -1.634e-06 -5.819e-03
total_cu_tl inq_last_12m annual_inc_merged
-4.751e-02 5.149e-02 -1.120e-05
dti_merged mths_since_delinq_cat mths_since_last_record_cat
5.727e-02 -2.382e-01 -9.641e-02
mths_since_last_major_derog_cat
-1.312e-01
[[7]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.292e+00 1.187e-04 2.387e-03
home_ownership verification_status purpose
1.676e-01 8.765e-01 3.491e-01
addr_state delinq_2yrs earliest_cr_line
1.294e-03 1.753e-02 2.087e-09
inq_last_6mths open_acc pub_rec
1.026e+00 6.105e-02 4.709e-01
revol_bal revol_util total_acc
3.357e-06 4.449e-02 -3.498e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-6.449e-01 2.629e-01 1.268e+00
tot_coll_amt tot_cur_bal open_acc_6m
1.447e-05 -1.594e-06 -7.157e-02
open_il_6m open_il_12m open_il_24m
-4.692e-02 4.124e-01 8.638e-02
mths_since_rcnt_il total_bal_il il_util
-7.308e-03 9.496e-07 -5.300e-03
open_rv_12m open_rv_24m max_bal_bc
7.600e-02 1.171e-01 -7.151e-05
all_util total_rev_hi_lim inq_fi
-8.874e-03 -1.923e-05 1.056e-02
total_cu_tl inq_last_12m annual_inc_merged
1.132e-02 3.502e-02 -3.045e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
7.089e-02 -2.075e-01 -1.125e-01
mths_since_last_major_derog_cat
-1.654e-01
[[8]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.209e+00 1.248e-04 1.160e-02
home_ownership verification_status purpose
1.773e-01 8.651e-01 3.504e-01
addr_state delinq_2yrs earliest_cr_line
5.853e-04 3.050e-02 2.052e-09
inq_last_6mths open_acc pub_rec
9.914e-01 6.241e-02 4.580e-01
revol_bal revol_util total_acc
5.356e-06 4.453e-02 -3.211e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-6.198e-01 3.945e-01 1.584e+00
tot_coll_amt tot_cur_bal open_acc_6m
4.597e-05 -1.178e-06 5.436e-02
open_il_6m open_il_12m open_il_24m
-2.002e-01 8.935e-01 -1.549e-01
mths_since_rcnt_il total_bal_il il_util
-1.179e-02 2.674e-06 -3.619e-03
open_rv_12m open_rv_24m max_bal_bc
1.913e-01 5.839e-02 -3.624e-05
all_util total_rev_hi_lim inq_fi
-5.312e-03 -2.178e-05 1.241e-01
total_cu_tl inq_last_12m annual_inc_merged
-5.658e-02 4.237e-02 -6.659e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
6.692e-02 -1.977e-01 -1.024e-01
mths_since_last_major_derog_cat
-1.458e-01
[[9]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.183e+00 1.192e-04 -3.819e-03
home_ownership verification_status purpose
1.472e-01 8.480e-01 3.663e-01
addr_state delinq_2yrs earliest_cr_line
3.031e-03 -1.195e-02 2.066e-09
inq_last_6mths open_acc pub_rec
9.837e-01 5.603e-02 4.285e-01
revol_bal revol_util total_acc
5.150e-06 4.455e-02 -2.954e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-6.202e-01 1.077e-01 7.956e-01
tot_coll_amt tot_cur_bal open_acc_6m
3.526e-05 -1.392e-06 2.585e-02
open_il_6m open_il_12m open_il_24m
-1.490e-01 6.185e-01 2.844e-02
mths_since_rcnt_il total_bal_il il_util
-4.387e-03 4.846e-07 -8.214e-04
open_rv_12m open_rv_24m max_bal_bc
4.166e-02 1.129e-01 -8.249e-05
all_util total_rev_hi_lim inq_fi
-5.746e-03 -2.086e-05 -2.847e-02
total_cu_tl inq_last_12m annual_inc_merged
-8.818e-02 7.265e-02 -4.097e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
6.711e-02 -2.058e-01 -1.159e-01
mths_since_last_major_derog_cat
-1.271e-01
[[10]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt emp_length
6.620e+00 1.237e-04 3.628e-03
home_ownership verification_status purpose
1.518e-01 8.846e-01 3.535e-01
addr_state delinq_2yrs earliest_cr_line
2.738e-04 5.111e-02 2.013e-09
inq_last_6mths open_acc pub_rec
1.007e+00 6.695e-02 3.318e-01
revol_bal revol_util total_acc
5.070e-06 4.422e-02 -3.177e-02
initial_list_status collections_12_mths_ex_med acc_now_delinq
-6.139e-01 1.075e-01 1.207e+00
tot_coll_amt tot_cur_bal open_acc_6m
2.896e-05 -1.315e-06 5.319e-02
open_il_6m open_il_12m open_il_24m
-1.678e-01 4.041e-01 9.409e-02
mths_since_rcnt_il total_bal_il il_util
-1.282e-02 1.377e-06 1.857e-04
open_rv_12m open_rv_24m max_bal_bc
3.216e-01 -1.583e-02 -9.745e-05
all_util total_rev_hi_lim inq_fi
-2.326e-03 -2.255e-05 4.121e-02
total_cu_tl inq_last_12m annual_inc_merged
-1.113e-01 7.710e-02 -5.135e-06
dti_merged mths_since_delinq_cat mths_since_last_record_cat
6.467e-02 -1.850e-01 -2.054e-01
mths_since_last_major_derog_cat
-1.184e-01
print(results)
#### Decision Trees ####
# Error in tree: "factor predictors must have at most 32 levels" is thrown.
# Basically, it becomes computationally expensive to create so many splits in your data, since you are selecting the best split out of all 2^32 (approx) possible splits.
# Fit a decision tree model on the training data
#tm <- tree(int_rate ~ ., data = sampled_train_data)
# Make predictions on the training and testing data
#tm.train_predictions <- predict(tm, newdata = sampled_train_data)
#tm.test_predictions <- predict(tm, newdata = sampled_test_data)
# Calculate Mean Squared Error (MSE) for training and testing
#tm.train_mse <- mean((tm.train_predictions - sampled_train_data$int_rate)^2)
#tm.test_mse <- mean((tm.test_predictions - sampled_test_data$int_rate)^2)
# Calculate Root Mean Squared Error (RMSE) for training and testing
#tm.train_rmse <- sqrt(tm.train_mse)
#tm.test_rmse <- sqrt(tm.test_mse)
# Calculate Mean Absolute Error (MAE) for training and testing
#tm.train_mae <- mean(abs(tm.train_predictions - sampled_train_data$int_rate))
#tm.test_mae <- mean(abs(tm.test_predictions - sampled_test_data$int_rate))
# Calculate R-squared (R²) for training and testing
#tm.train_r2 <- 1 - (sum((sampled_train_data$int_rate - tm.train_predictions)^2) / sum((sampled_train_data$int_rate - mean(sampled_train_data$int_rate))^2))
#tm.test_r2 <- 1 - (sum((sampled_test_data$int_rate - tm.test_predictions)^2) / sum((sampled_test_data$int_rate - mean(sampled_test_data$int_rate))^2))
# Display the metrics
#cat("Training MSE:", tm.train_mse, "\n")
#cat("Testing MSE:", tm.test_mse, "\n")
#cat("Training RMSE:", tm.train_rmse, "\n")
#cat("Testing RMSE:", tm.test_rmse, "\n")
#cat("Training MAE:", tm.train_mae, "\n")
#cat("Testing MAE:", tm.test_mae, "\n")
#cat("Training R-squared (R²):", tm.train_r2, "\n")
#cat("Testing R-squared (R²):", tm.test_r2, "\n")
#### Random Forest ####
# Train a Random Forest model
rf <- ranger(formula = int_rate ~ ., data = sampled_train_data, num.trees = 500, verbose=TRUE, importance = "impurity", oob.error = TRUE)
Growing trees.. Progress: 11%. Estimated remaining time: 4 minutes, 0 seconds.
Growing trees.. Progress: 24%. Estimated remaining time: 3 minutes, 17 seconds.
Growing trees.. Progress: 37%. Estimated remaining time: 2 minutes, 41 seconds.
Growing trees.. Progress: 50%. Estimated remaining time: 2 minutes, 7 seconds.
Growing trees.. Progress: 63%. Estimated remaining time: 1 minute, 33 seconds.
Growing trees.. Progress: 75%. Estimated remaining time: 1 minute, 2 seconds.
Growing trees.. Progress: 87%. Estimated remaining time: 33 seconds.
Growing trees.. Progress: 99%. Estimated remaining time: 1 seconds.
# Print the model summary
print("Random Forest Model Summary:")
[1] "Random Forest Model Summary:"
print(rf)
Ranger result
Call:
ranger(formula = int_rate ~ ., data = sampled_train_data, num.trees = 500, verbose = TRUE, importance = "impurity", oob.error = TRUE)
Type: Regression
Number of trees: 500
Sample size: 638392
Number of independent variables: 39
Mtry: 6
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 11.08217
R squared (OOB): 0.4229489
# Make predictions on the training and testing data
rf.train_predictions <- predict(rf, data = sampled_train_data)
Predicting.. Progress: 73%. Estimated remaining time: 11 seconds.
rf.test_predictions <- predict(rf, data = sampled_test_data)
# Calculate Mean Squared Error (MSE) for training and testing
rf.train_mse <- mean((rf.train_predictions$predictions - sampled_train_data$int_rate)^2)
rf.test_mse <- mean((rf.test_predictions$predictions - sampled_test_data$int_rate)^2)
# Calculate Root Mean Squared Error (RMSE) for training and testing
rf.train_rmse <- sqrt(rf.train_mse)
rf.test_rmse <- sqrt(rf.test_mse)
# Calculate Mean Absolute Error (MAE) for training and testing
rf.train_mae <- mean(abs(rf.train_predictions$predictions - sampled_train_data$int_rate))
rf.test_mae <- mean(abs(rf.test_predictions$predictions - sampled_test_data$int_rate))
# Calculate R-squared (R²) for training and testing
rf.train_r2 <- 1 - (sum((sampled_train_data$int_rate - rf.train_predictions$predictions)^2) / sum((sampled_train_data$int_rate - mean(sampled_train_data$int_rate))^2))
rf.test_r2 <- 1 - (sum((sampled_test_data$int_rate - rf.test_predictions$predictions)^2) / sum((sampled_test_data$int_rate - mean(sampled_test_data$int_rate))^2))
# Display the metrics
cat("Training MSE:", rf.train_mse, "\n")
Training MSE: 2.572857
cat("Testing MSE:", rf.test_mse, "\n")
Testing MSE: 11.01728
cat("Training RMSE:", rf.train_rmse, "\n")
Training RMSE: 1.604013
cat("Testing RMSE:", rf.test_rmse, "\n")
Testing RMSE: 3.319228
cat("Training MAE:", rf.train_mae, "\n")
Training MAE: 1.260271
cat("Testing MAE:", rf.test_mae, "\n")
Testing MAE: 2.6258
cat("Training R-squared (R²):", rf.train_r2, "\n")
Training R-squared (R²): 0.8660306
cat("Testing R-squared (R²):", rf.test_r2, "\n")
Testing R-squared (R²): 0.4260632
#rf <- randomForest(int_rate~., data=train_data, ntree = 5, mtry = 3)
#bag.boston=randomForest(medv~.,data=Boston,subset=train, mtry=13,importance =TRUE)
#print(rf)
# Set the number of cores you want to use
#num_cores <- 6 # Adjust this number based on your system's capabilities
# Register parallel backend
#cl <- makeCluster(num_cores)
#registerDoParallel(cl)
# Assuming 'lc_data' is your dataset
#rf_model <- foreach(ntree = rep(100, num_cores), .packages = 'randomForest') %dopar% {
# randomForest(int_rate ~ ., data = lc_data, ntree = ntree, mtry = sqrt(ncol(lc_data)))
#}
# After training, stop the cluster to release the cores:
#stopCluster(cl)
#### Boosting ####
# Define the target variable for training and testing
xgb.y_train <- sampled_train_data$int_rate
xgb.y_test <- sampled_test_data$int_rate # Use sampled_test_data for testing
# Define the feature matrix for training and testing (exclude the target variable)
xgb.X_train <- sampled_train_data[, -which(names(sampled_train_data) == 'int_rate')]
xgb.X_test <- sampled_test_data[, -which(names(sampled_test_data) == 'int_rate')] # Use sampled_test_data for testing
# Fit a gradient boosting regression model using xgboost
xgb <- xgboost(
data = as.matrix(xgb.X_train),
label = xgb.y_train,
nrounds = 100,
verbose = 0
)
# Make predictions on the training and testing data
xgb.train_predictions <- predict(xgb, newdata = as.matrix(xgb.X_train))
xgb.test_predictions <- predict(xgb, newdata = as.matrix(xgb.X_test))
# Calculate Mean Squared Error (MSE) for training and testing
xgb.train_mse <- mean((xgb.train_predictions - xgb.y_train)^2)
xgb.test_mse <- mean((xgb.test_predictions - xgb.y_test)^2)
# Calculate Root Mean Squared Error (RMSE) for training and testing
xgb.train_rmse <- sqrt(xgb.train_mse)
xgb.test_rmse <- sqrt(xgb.test_mse)
# Calculate Mean Absolute Error (MAE) for training and testing
xgb.train_mae <- mean(abs(xgb.train_predictions - xgb.y_train))
xgb.test_mae <- mean(abs(xgb.test_predictions - xgb.y_test))
# Calculate R-squared (R²) for training and testing
xgb.train_r2 <- 1 - (sum((xgb.y_train - xgb.train_predictions)^2) / sum((xgb.y_train - mean(xgb.y_train))^2))
xgb.test_r2 <- 1 - (sum((xgb.y_test - xgb.test_predictions)^2) / sum((xgb.y_test - mean(xgb.y_test))^2))
# Display the metrics
cat("Training MSE:", xgb.train_mse, "\n")
Training MSE: 9.918589
cat("Testing MSE:", xgb.test_mse, "\n")
Testing MSE: 10.29675
cat("Training RMSE:", xgb.train_rmse, "\n")
Training RMSE: 3.149379
cat("Testing RMSE:", xgb.test_rmse, "\n")
Testing RMSE: 3.208854
cat("Training MAE:", xgb.train_mae, "\n")
Training MAE: 2.475425
cat("Testing MAE:", xgb.test_mae, "\n")
Testing MAE: 2.522647
cat("Training R-squared (R²):", xgb.train_r2, "\n")
Training R-squared (R²): 0.4835362
cat("Testing R-squared (R²):", xgb.test_r2, "\n")
Testing R-squared (R²): 0.4635987
Following, a scatter plot of actual vs predicted training values for each model is plot. This plot helps us visualize how well each model’s predictions align with the actual data points.
# Create a scatter plot function
create_scatter_plot <- function(actual_values, predicted_values, model_name) {
model_comparison_data <- data.frame(
Actual = actual_values,
Predicted = predicted_values
)
scatter_plot <- ggplot(model_comparison_data, aes(x = Actual, y = Predicted)) +
geom_point() +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", color = "red") + # Add a diagonal reference line
labs(x = "Actual Training Values", y = "Predicted Training Values", title = model_name) +
theme_minimal() +
ylim(-50, 50)
return(scatter_plot)
}
# Create scatter plots for each model
lm_scatter_plot <- create_scatter_plot(
actual_values = sampled_train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_scatter_plot <- create_scatter_plot(
actual_values = sampled_train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_scatter_plot <- create_scatter_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# Display the scatter plots separately
print(lm_scatter_plot)
print(rf_scatter_plot)
print(xgb_scatter_plot)
Following, a scatter plot of actual vs predicted testing values for each model is plot. This plot helps us visualize how well each model’s predictions align with the actual data points.
# Create a scatter plot function
create_scatter_plot <- function(actual_values, predicted_values, model_name) {
model_comparison_data <- data.frame(
Actual = actual_values,
Predicted = predicted_values
)
scatter_plot <- ggplot(model_comparison_data, aes(x = Actual, y = Predicted)) +
geom_point() +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", color = "red") + # Add a diagonal reference line
labs(x = "Actual Testing Values", y = "Predicted Testing Values", title = model_name) +
theme_minimal() +
ylim(-50, 50)
return(scatter_plot)
}
# Create scatter plots for each model
lm_scatter_plot <- create_scatter_plot(
actual_values = sampled_test_data$int_rate,
predicted_values = lm.test_predictions,
model_name = "Linear Regression"
)
rf_scatter_plot <- create_scatter_plot(
actual_values = sampled_test_data$int_rate,
predicted_values = rf.test_predictions$predictions,
model_name = "Random Forest"
)
xgb_scatter_plot <- create_scatter_plot(
actual_values = xgb.y_test,
predicted_values = xgb.test_predictions,
model_name = "XGBoost"
)
# Display the scatter plots separately
print(lm_scatter_plot)
print(rf_scatter_plot)
print(xgb_scatter_plot)
Residual plots can help identify patterns in prediction errors and assess whether the assumptions of linear regression (if applicable) are met.
# Create a residual plot function
create_residual_plot <- function(actual_values, predicted_values, model_name) {
residuals <- actual_values - predicted_values
residual_data <- data.frame(
Predicted = predicted_values,
Residuals = residuals
)
residual_plot <- ggplot(residual_data, aes(x = Predicted, y = Residuals)) +
geom_point() +
geom_hline(yintercept = 0, linetype = "dashed", color = "red") + # Red horizontal reference line
labs(x = "Predicted Values", y = "Residuals", title = paste("Residual Plot -", model_name)) +
theme_minimal() +
ylim(-30, 30) +
xlim(0, 40)
return(residual_plot)
}
# Create residual plots for each model
lm_residual_plot <- create_residual_plot(
actual_values = sampled_train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_residual_plot <- create_residual_plot(
actual_values = sampled_train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_residual_plot <- create_residual_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# Display the residual plots separately
print(lm_residual_plot)
print(rf_residual_plot)
print(xgb_residual_plot)
From the plots above we can clearly see that:
This visualization can help you compare the distribution of prediction errors across models.
# Create a density plot function for residuals
create_residual_density_plot <- function(actual_values, predicted_values, model_name) {
residuals <- actual_values - predicted_values
residual_data <- data.frame(Residuals = residuals)
density_plot <- ggplot(residual_data, aes(x = Residuals)) +
geom_density(fill = "skyblue", color = "black", alpha = 0.7) +
labs(x = "Residuals", y = "Density", title = paste("Residual Density Plot -", model_name)) +
theme_minimal()
return(density_plot)
}
# Create density plots for residuals for each model
lm_residual_density_plot <- create_residual_density_plot(
actual_values = sampled_train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_residual_density_plot <- create_residual_density_plot(
actual_values = sampled_train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_residual_density_plot <- create_residual_density_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# Display the density plots separately
print(lm_residual_density_plot)
print(rf_residual_density_plot)
print(xgb_residual_density_plot)
This visualization can help you compare the distribution of prediction errors across models through histograms.
# Create a histogram plot function for residuals with a red density curve
create_residual_histogram_plot <- function(actual_values, predicted_values, model_name) {
residuals <- actual_values - predicted_values
residual_data <- data.frame(Residuals = residuals)
histogram_plot <- ggplot(residual_data, aes(x = Residuals)) +
geom_histogram(aes(y = after_stat(density)), bins = 30, fill = "skyblue", color = "black", alpha = 0.7) + # Use density on the y-axis for the histogram
geom_density(color = "red", linewidth = 1.5) + # Add the density plot in red
labs(x = "Residuals", y = "Density", title = paste("Residual Histogram Plot with Density Curve -", model_name)) +
theme_minimal() +
xlim(-20,20) +
ylim(0, 0.3)
return(histogram_plot)
}
# Create histogram plots for residuals for each model
lm_residual_histogram_plot <- create_residual_histogram_plot(
actual_values = sampled_train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_residual_histogram_plot <- create_residual_histogram_plot(
actual_values = sampled_train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_residual_histogram_plot <- create_residual_histogram_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# Display the histogram plots separately
print(lm_residual_histogram_plot)
print(rf_residual_histogram_plot)
print(xgb_residual_histogram_plot)
For each model a bar chart that displays the R-squared (coefficient of determination) values is created. R-squared measures the proportion of variance in the target variable explained by the model. Higher R-squared values indicate better model fit.
# Create a data frame with R-squared values for each model
model_names <- c("Linear Regression", "Random Forest", "XGBoost")
r_squared_values <- c(
lm.train_r2,
rf.train_r2,
xgb.train_r2
)
r_squared_data <- data.frame(Model = factor(model_names),
R_squared = r_squared_values)
# Create the R-squared comparison bar chart
r_squared_bar_chart <- ggplot(r_squared_data, aes(x = Model, y = R_squared, fill = Model)) +
geom_bar(stat = "identity") +
labs(x = "Model", y = "R-squared (R²)", title = "R-squared Comparison") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
# Display the R-squared comparison bar chart
print(r_squared_bar_chart)
A bar chart that compares the MAE or RMSE values, is generated for each model. These metrics quantify the average prediction errors of each model, and lower values are preferred.
# Create a data frame with MAE and RMSE values for each model
model_names <- c("Linear Regression", "Random Forest", "XGBoost","Linear Regression", "Random Forest", "XGBoost")
error_values_train <- c(
lm.train_mae,
rf.train_mae,
xgb.train_mae,
lm.train_rmse,
rf.train_rmse,
xgb.train_rmse
)
error_values_test <- c(
lm.test_mae,
rf.test_mae,
xgb.test_mae,
lm.test_rmse,
rf.test_rmse,
xgb.test_rmse
)
error_type <- c(
"MAE", "MAE", "MAE","RMSE","RMSE","RMSE"
)
model_errors_train <- data.frame(Model = factor(model_names, levels = c("Linear Regression", "Random Forest", "XGBoost")),
Error = error_values_train, Type = error_type)
model_errors_test <- data.frame(Model = factor(model_names, levels = c("Linear Regression", "Random Forest", "XGBoost")),
Error = error_values_test, Type = error_type)
# Create the MAE or RMSE comparison bar chart
error_bar_chart_train <- ggplot(model_errors_train, aes(x = Model, y = Error, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "Model", y = "Error Value", title = "Training MAE and RMSE Comparison") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0, 4)
error_bar_chart_test <- ggplot(model_errors_test, aes(x = Model, y = Error, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "Model", y = "Error Value", title = "Testing MAE and RMSE Comparison") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0, 4)
# Display the MAE and RMSE comparison bar chart
print(error_bar_chart_train)
print(error_bar_chart_test)
#### Random Forest Feature Importance Plot ####
v1 <- vip(rf, title = "Ranger", num_features = 20)
plot(v1)
Learning curve using RMSE and R^2:
# TODO: change the x-axes
# Create a data frame with RMSE and R-squared values for each model and sample size
model_names <- c("Linear Regression", "Random Forest", "XGBoost")
sample_sizes <- seq(10, nrow(sampled_train_data), by = 10) # Adjust the sample sizes as needed
# Create data frames with RMSE and R-squared values for each model
rmse_data <- data.frame(
Model = rep(model_names, each = length(sample_sizes)),
Sample_Size = rep(sample_sizes, times = length(model_names)),
RMSE = c(
lm.train_rmse, rf.train_rmse, xgb.train_rmse
)
)
r_squared_data <- data.frame(
Model = rep(model_names, each = length(sample_sizes)),
Sample_Size = rep(sample_sizes, times = length(model_names)),
R_squared = c(
lm.train_r2, rf.train_r2, xgb.train_r2
)
)
# Create RMSE learning curve
rmse_curve <- ggplot(rmse_data, aes(x = Sample_Size, y = RMSE, color = Model)) +
geom_line() +
labs(x = "Sample Size", y = "RMSE", title = "RMSE Learning Curve") +
theme_minimal()
# Create R-squared learning curve
r_squared_curve <- ggplot(r_squared_data, aes(x = Sample_Size, y = R_squared, color = Model)) +
geom_line() +
labs(x = "Sample Size", y = "R-squared", title = "R-squared Learning Curve") +
theme_minimal()
# Display the RMSE and R-squared learning curves
print(rmse_curve)
print(r_squared_curve)
Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Ctrl+Alt+I.
When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Ctrl+Shift+K to preview the HTML file).
The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.